package cn.online.zhuanshenben.web;

import cn.online.zhuanshenben.vo.Result;
import com.alibaba.fastjson2.JSON;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

/**
 * @author oldliu
 * @since 1.0
 */
public class BaseServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doOptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setHeader("Access-Control-Allow-Origin", req.getHeader("origin"));
        resp.setHeader("Access-Control-Allow-Methods", "POST,GET,PUT,OPTIONS,DELETE");
        resp.setHeader("Access-Control-Max-Age", "3600");
        resp.setHeader("Access-Control-Allow-Credentials", "true");
        resp.setHeader("Access-Control-Allow-Headers", "*");
        resp.setHeader("Access-Control-Request-Headers","*");

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("application/json;charset=utf-8");
        resp.setHeader("Access-Control-Allow-Origin", req.getHeader("origin"));
        resp.setHeader("Access-Control-Allow-Methods", "POST,GET,PUT,OPTIONS,DELETE");
        resp.setHeader("Access-Control-Max-Age", "3600");
        resp.setHeader("Access-Control-Allow-Credentials", "true");
        resp.setHeader("Access-Control-Allow-Headers", "*");
        resp.setHeader("Access-Control-Request-Headers","*");


        String path = req.getServletPath();
        path = path.substring(1, path.lastIndexOf('.'));//
        System.out.println(path);
        try {
            Method m = this.getClass().getDeclaredMethod(path, HttpServletResponse.class, HttpServletRequest.class);
            Object r = m.invoke(this, resp, req);
            if (r == null)
                return;
            if (r instanceof String) {
                //认为是转发地址
                resp.setContentType("text/html;charset=utf-8");
                req.getRequestDispatcher((String) r).forward(req, resp);
                return;
            }
            //其他情况，发json对象
            resp.getWriter().print(JSON.toJSONString(r));
        } catch (Exception e) {
            //writer.println("出现了异常：" + e);
            e.printStackTrace();
            resp.getWriter().print(JSON.toJSONString(Result.error(String.valueOf("出现错误:" + e))));
        }
    }
}
